<template>
  <el-form-item label="商品图文介绍" prop="detailText">
    <div class="text-box" v-if="!flag" v-html="formatStr(initialValue)">
    </div>
    <rich-editor v-if="flag" ref="richEditorRef" :initial-value="props.initialValue"
      @change="handleDetailTextChange"></rich-editor>
  </el-form-item>
</template>

<script lang="ts" setup>
const props = withDefaults(defineProps<{
  initialValue: string,
  modelValue: string
}>(), {
  initialValue: '',
  modelValue: ''
})

//商品图文是否仅仅预览
const flag = ref(true)
watch(() => props.initialValue, (val) => {
  flag.value = canEdit(val)
})

const emits = defineEmits(['update:model-value'])

const richEditorRef = ref()

const handleDetailTextChange = ({ innerHTML }: { innerHTML: string }) => {
  // console.log('inner html', innerHTML)
  emits("update:model-value", innerHTML)
}

const rules = [{ message: '请输入商品图文介绍', required: true, trigger: 'blur' }]

//替换富文本字符
const formatStr = (str) => {
  return str.replaceAll(/\\n/g, '')
}

//判断富文本是否可以编辑
const canEdit = (text) => {
  if (text && typeof text == 'string') {
    if (text.startsWith('<style>')) {
      return false
    }
    return true

  }
  return true
}

// onMounted(() => {
//   richEditorRef.value?.insertHTML(props.initialValue)
// })

// onBeforeUnmount(() => {
//   richEditorRef.value?.clearEditor()
// })
</script>

<style scoped lang="scss">
.text-box {
  overflow: auto;
  width: 100%;
  max-height: 60vh;
  border: 1px solid var(--el-border-color);
}
</style>
